import userService from '../../api/user'; // ✅ 推荐使用 ES6 导入

Page({
  data: {
    phoneNumber: '',
    smsCode: '',
    password: ''
  },

  handleInputPhone(e) {
    this.setData({ phoneNumber: e.detail.value });
  },

  handleInputCode(e) {
    this.setData({ smsCode: e.detail.value });
  },

  handleInputPassword(e) {
    this.setData({ password: e.detail.value });
  },

  getVerificationCode() {
    const phoneNumber = this.data.phoneNumber;
    if (!this.validatePhoneNumber(phoneNumber)) {
      wx.showToast({ title: '手机号输入错误', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '发送中...' });
    userService.sendSmsCode({ mobile: phoneNumber, codeType: 'register' })
      .then(res => {
        wx.hideLoading();
        if (res.code === 200) {
          wx.showToast({ title: '验证码发送成功', icon: 'success' });
        } else {
          wx.showToast({ title: res.msg || '发送失败', icon: 'none' });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('验证码发送失败:', err);
        wx.showToast({ title: '网络异常', icon: 'none' });
      });
  },

  register() {
    const { phoneNumber, smsCode, password } = this.data;
  
    if (!this.validatePhoneNumber(phoneNumber)) {
      wx.showToast({ title: '手机号格式错误', icon: 'none' });
      return;
    }
  
    if (!smsCode || !password) {
      wx.showToast({ title: '验证码或密码不能为空', icon: 'none' });
      return;
    }
  
    wx.showLoading({ title: '注册中...' });
  
    console.log('注册请求参数:', {
      username: phoneNumber,
      password:password,
      mobile: phoneNumber,
      code: smsCode
    });
  
    userService.register({
      username: phoneNumber,
      password:password,
      mobile: phoneNumber,
      code: smsCode
    }).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        wx.showToast({ title: '注册成功', icon: 'success' });
        setTimeout(() => {
          wx.redirectTo({ url: '/pages/my/login/login' }); // 确认路径正确
        }, 1000);
      } else {
        wx.showToast({ title: res.msg || '注册失败', icon: 'none' });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('注册失败:', err);
      wx.showToast({ title: '网络异常', icon: 'none' });
    });
  },  

  validatePhoneNumber(phone) {
    const reg = /^1[3-9]\d{9}$/; // ✅ 正确正则
    return reg.test(phone);
  }
});
